package com.haoc.a520demo;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.haoc.a520demo.utils.Myutils;
import com.huawei.agconnect.applinking.AGConnectAppLinking;
import com.huawei.agconnect.applinking.AppLinking;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;

public class PhotoActivity extends Activity {
    private static final String DOMAIN_URI_PREFIX = "https://520.drcn.agconnect.link";
    private String uri;
    private static String App_LinkingUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo);
        uri = getIntent().getStringExtra("Url");
        init();
        // 设置状态栏效果
        Myutils.setStatusBar(PhotoActivity.this);
    }

    private void init() {
        ImageView image = findViewById(R.id.image);
        // 加载云存储上的图片
        Picasso.with(PhotoActivity.this)
                .load(uri)
                .networkPolicy(NetworkPolicy.NO_CACHE)
                .memoryPolicy(MemoryPolicy.NO_CACHE)
                .into(image);
        ImageView img_share = findViewById(R.id.img_share);
        img_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                createAppLinking();
                shareLink(App_LinkingUrl);
            }
        });
    }

    // 创建App Linking
    private void createAppLinking() {
        AppLinking.Builder builder = AppLinking.newBuilder()
                .setUriPrefix(DOMAIN_URI_PREFIX)
                .setDeepLink(Uri.parse(uri))
                .setAndroidLinkInfo(AppLinking.AndroidLinkInfo.newBuilder()
                        .setAndroidDeepLink(uri)
                        .build());
        builder.buildShortAppLinking().addOnSuccessListener(shortAppLinking -> {
            Uri shortLinkUri = shortAppLinking.getShortUrl();
            App_LinkingUrl = shortLinkUri.toString();
        }).addOnFailureListener(e -> {
            //AppLinkingException
            Log.i("failed", "" + e.getMessage());
        });
    }

    // 分享链接
    private void shareLink(String LinkingUrl) {
        if (LinkingUrl != null) {
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_TEXT, LinkingUrl);
            startActivity(intent);
        }
    }
}